package dubbo.learn.cluster;

import dubbo.learn.cluster.loadbalance.LoadBalancePolicy;
import dubbo.learn.common.ProviderHostAndPort;
import dubbo.learn.common.RpcContext;
import dubbo.learn.common.contract.cluster.ClusterLayerRpcInvoker;
import dubbo.learn.common.contract.exchange.ExchangeLayerRpcInvoker;
import dubbo.learn.common.spi.SpiServiceLoader;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 请求失败以后，返回异常结果，不进行重试。
 */
@Slf4j
@Service
public class FailfastClusterLayerRpcInvoker implements ClusterLayerRpcInvoker {

    @Autowired
    private LoadBalancePolicy loadBalancePolicy;


    @Override
    public Object invoke(List<ProviderHostAndPort> providerList, RpcContext rpcContext) {
        ExchangeLayerRpcInvoker exchangeLayerRpcInvoker =
                SpiServiceLoader.loadService(ExchangeLayerRpcInvoker.class);

        ProviderHostAndPort providerHostAndPort = loadBalancePolicy.selectOne(providerList);
        try {
            Object o = exchangeLayerRpcInvoker.invoke(providerHostAndPort, rpcContext);
            return o;
        } catch (Exception e) {
            log.error("fail to invoke {},will try another",providerHostAndPort);
            throw e;
        }
    }
}
